<template>
  <div class="cg-input">
    <input
      v-if="type !== 'textarea'"
      ref="input"
      type="text"
      :placeholder="placeholder"
      :value="data"
      @input.stop="handleInput"
    />
    <textarea
      v-if="type === 'textarea'"
      ref="textarea"
      :placeholder="placeholder"
      :value="data"
      @input.stop="handleInput"
      :style="textareaStyle"
    ></textarea>
  </div>
</template>

<script>
import { merge } from "../../tools/index";
import { calcTextareaHeight } from "./util";
export default {
  name: "cg-input",
  props: {
    modelValue: [String, Number],
    placeholder: {
      type: String,
      default: "请输入",
    },
    type: String,
    resize: String,
    autosize: {
      type: [Boolean, Object],
      default: false,
    },
  },
  data() {
    return {
      textareaCalcStyle: {},
      data: this.modelValue,
    };
  },
  computed: {
    textareaStyle() {
      return merge({}, this.textareaCalcStyle, { resize: this.resize });
    },
  },
  watch: {
    modelValue(val) {
      this.data = val;
      this.$nextTick(this.resizeTextarea);
    },
    type() {
      this.$nextTick(() => {
        this.resizeTextarea();
      });
    },
  },
  mounted() {
    this.resizeTextarea();
  },
  methods: {
    handleInput(event) {
      let inputValue = event.target.value;
      if (inputValue === this.nativeInputValue) return;
      this.data = inputValue;
      this.$emit("update:modelValue", inputValue);
    },
    resizeTextarea() {
      const { autosize, type } = this;
      if (type !== "textarea") return;
      if (!autosize) {
        this.textareaCalcStyle = {
          minHeight: calcTextareaHeight(this.$refs.textarea).minHeight,
        };
        return;
      }
      const minRows = autosize.minRows;
      const maxRows = autosize.maxRows;
      this.textareaCalcStyle = calcTextareaHeight(
        this.$refs.textarea,
        minRows,
        maxRows
      );
    },
  },
};
</script>

<style lang="scss">
.cg-input {
  padding: 0 1em;
  background: #f2f2f2;
  display: inline-block;
  input {
    background: none;
    font-size: 1em;
    line-height: 2em;
    letter-spacing: 0px;
    border: none;
    outline: unset;
    width: 100%;
    -webkit-appearance: none;
    color: #606266;
  }

  &:focus {
    outline: none;
  }

  textarea {
    background: none;
    font-size: 1em;
    display: block;
    resize: vertical;
    line-height: 1.5em;
    box-sizing: border-box;
    width: 100%;
    color: #606266;
    border: none;
    outline: unset;
  }
}
</style>
